package org.qiancizhan.UI;

import org.qiancizhan.Config.RedisConfig;
import org.qiancizhan.Controller.AIConversationController;
import org.qiancizhan.Model.DTO.AIConversationContentDTO;
import org.qiancizhan.Model.POJO.AIConversationContentPOJO;
import org.qiancizhan.Model.POJO.AIConversationPOJO;
import org.qiancizhan.Model.POJO.UserPOJO;
import org.qiancizhan.Utils.ThreadLocalUtil;
import org.qiancizhan.Utils.UIFormatUtli;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;

import org.qiancizhan.Utils.LoadingAnimationUtil;
import redis.clients.jedis.Jedis;

public class AssistantUI {
    private static final Jedis redis = RedisConfig.getInstance();
    private static final Scanner sc = new Scanner(System.in);
    private static final AIConversationController aiConversationController = new AIConversationController();

    public static void showAssistantMenu() {
        while (true) {
            UIFormatUtli.log("欢迎使用AI助手!");
            System.out.println("本AI采用的是ALiYun通义千问");
            System.out.println("1.小爱英语老师\t2.开启新对话\t3.选择历史对话\t0.退出");
            switch (sc.nextLine().trim()) {
                case "1" -> {
                    XiaoAiFn(false, null, null);
                }
                case "2" -> {
                    newAIFn(false, null, null);
                }
                case "3" -> {
                    selectHistoryFn();
                }
                case "0" -> {
                    System.out.println("退出AI助手");
                    return;
                }
                default -> {
                    System.out.println("请输入正确的选项");
                }
            }
        }
    }

    private static void selectHistoryFn() {
        List<AIConversationPOJO> userAIConversationList = aiConversationController.getUserAIConversationList();
        if (userAIConversationList == null) {
            UIFormatUtli.log("没有历史对话");
            return;
        }
        for (int i = 0; i < userAIConversationList.size(); i++) {
            String format = String.format("%d:%s\t%s", (i + 1), userAIConversationList.get(i).getTitle().length() <= 15 ? userAIConversationList.get(i).getTitle() : userAIConversationList.get(i).getTitle().substring(0, 15) + "...", userAIConversationList.get(i).getIsXiaoAi() == 1 ? "[老师]" : "[AI]");
            System.out.println(format);
        }
        System.out.println("请选择要查看的对话：\t[n].选择第n个对话\tclear.清空历史对话\t0.退出");
        String input = sc.nextLine().trim();
        while (true) {
            if ("0".equals(input)) return;
            else if ("clear".equals(input)) {
                while (true) {
                    System.out.println("确定要清空历史对话吗？[1/0]");
                    String sel = sc.nextLine().trim();
                    if ("1".equals(sel)) {
                        aiConversationController.clearConversation();
                        return;
                    } else if ("0".equals(sel)) return;
                    else System.out.println("请输入正确的选项");
                }
            } else if (input.matches("\\d+")) {
                int num = Integer.parseInt(input);
                if (num >= 1 && num <= userAIConversationList.size()) {
                    break;
                } else {
                    System.out.println("请输入正确的选项");
                    input = sc.nextLine().trim();
                }
            } else {
                System.out.println("请输入正确的选项");
                input = sc.nextLine().trim();
            }
        }
        int select = Integer.parseInt(input);
        AIConversationPOJO selectConversation = userAIConversationList.get(select - 1);
        List<AIConversationContentPOJO> userMessages = aiConversationController.getUserAIConversationContents(userAIConversationList.get(select - 1).getId());
        System.out.println(UIFormatUtli.HR);
        for (AIConversationContentPOJO message : userMessages) {
            if ("system".equals(message.getMessage_type())) continue;
            System.out.println();
            String prefix = "user".equals(message.getMessage_type()) ? "用户:" : (selectConversation.getIsXiaoAi() == 1 ? "小爱老师:" : "Assistant:");
            System.out.println(prefix + message.getMessage_content());
            System.out.println();
        }
        UIFormatUtli.log("以上是历史问话");
        List<AIConversationContentDTO> data = new ArrayList<>();
        for (AIConversationContentPOJO message : userMessages)
            data.add(new AIConversationContentDTO(message.getId(), message.getMessage_type(), message.getMessage_content()));

        if (selectConversation.getIsXiaoAi() == 1) XiaoAiFn(true, data, selectConversation);
        else newAIFn(true, data, selectConversation);
    }

    private static void newAIFn(boolean isInit, List<AIConversationContentDTO> userMessages, AIConversationPOJO selectConversation) {
        chatWithAI(isInit, userMessages, selectConversation, "Assistant", "我有什么可以帮助你的吗？", false);
    }

    public static void XiaoAiFn(boolean isInit, List<AIConversationContentDTO> userMessages, AIConversationPOJO selectConversation) {
        chatWithAI(isInit, userMessages, selectConversation, "小爱老师", "Hello！我是小爱老师，看到你来啦～今天想学点什么呀？[(●'◡'●)]", true);
    }

    private static void chatWithAI(boolean isInit, List<AIConversationContentDTO> userMessages,
                                   AIConversationPOJO selectConversation, String aiName,
                                   String welcomeMessage, boolean isXiaoAi) {
        System.out.println(aiName + "：" + welcomeMessage);
        List<AIConversationContentDTO> messages = isInit ? userMessages : new ArrayList<>();
        String title = isInit ? selectConversation.getTitle() : "";
        if (isXiaoAi && !isInit)
            aiConversationController.XiaoAiInit();
        while (true) {
            System.out.print("用户：");
            String input = sc.nextLine().trim();
            if (input.equals("0")) {
                System.out.println("退出聊天");
                if (isInit) {
                    List<AIConversationContentDTO> data = messages.stream()
                            .filter(message -> userMessages.stream()
                                    .noneMatch(userMessage -> userMessage.getId().equals(message.getId())))
                            .collect(Collectors.toList());
                    if (data.size() == 0) {
                        clearHistory();
                        return;
                    }
                    aiConversationController.addAIcontent(selectConversation.getId(), data);
                } else {
                    if (messages == null || messages.size() == 0) {
                        clearHistory();
                        return;
                    }
                    String conversationID = aiConversationController.addAIConversation(isXiaoAi, title, messages.size() - 1);
                    aiConversationController.addAIcontent(conversationID, messages);
                }
                clearHistory();
                return;
            }
            if (input.isEmpty()) {
                System.out.println("请输入内容");
                continue;
            }
            LoadingAnimationUtil.startLoading(aiName + "正在思考中...");
            try {
                messages = aiConversationController.sendMessage(input);
                String aiResponse = messages.get(messages.size() - 1).getMessage_content();
                if (title.equals("")) title = aiConversationController.generateTitle(messages);
                LoadingAnimationUtil.stopLoading();
                System.out.println();
                System.out.println(aiName + "：" + aiResponse);
            } catch (Exception e) {
                LoadingAnimationUtil.stopLoading();
                System.out.println();
                System.out.println(aiName + "：抱歉，我遇到了一些问题，请稍后再试");
                e.printStackTrace();
            }
        }
    }

    public static void clearHistory() {
        UserPOJO user = ThreadLocalUtil.get();
        String userKey = "user_" + user.getId();
        redis.del(userKey);
    }
}
